package bean

import (
	"github.com/gin-gonic/gin"
)

func (a *serverImpl) AllowedCORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 设置允许跨域的响应头
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*") // 允许所有域名跨域，生产环境可指定具体域名
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization")
		c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

		// 如果是预检请求，直接返回204状态码，不继续处理
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
